package com.woniu.service.impl;

import com.woniu.dao.OrderDao;
import com.woniu.entity.Order;
import com.woniu.entity.Product;
import com.woniu.entity.utils.ResponseEntity;
import com.woniu.service.OrderService;
import org.apache.commons.beanutils.BeanUtils;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.InvocationTargetException;
import java.util.Map;

//@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderDao orderDao;



    @Override
    public ResponseEntity generateOrder(Integer pid, Integer num) {
        //使用微服务调用方案
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity productResp = restTemplate.getForObject("http://localhost:8081/product/" + pid, ResponseEntity.class);

        //业务代码
        Product product = new Product();
        //处理获取不到数据
        if(Integer.parseInt(productResp.get(ResponseEntity.ResponseStatus.CODE.value())+"") == HttpStatus.INTERNAL_SERVER_ERROR.value()){
            return productResp;
        }

        Map map = (Map) productResp.get(ResponseEntity.ResponseStatus.DATA.value());
        //将数据存放到product对象中
        try {
            BeanUtils.populate(product, map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        Order order = new Order();
        //用户信息假数据
        order.setUid(1);
        order.setUsername("tom");
        order.setPid(product.getPid());
        order.setPname(product.getName());
        order.setPrice(product.getPrice());
        order.setNumber(num);

        Order returnOrder  = null;
        //订单入库成功，要删减库存
        if(product.getStock() - num >= 0){
            returnOrder = orderDao.save(order);
            product.setStock(product.getStock() - num);
            restTemplate.put("http://localhost:8081/product/" , product);
        }else{
            return new ResponseEntity(HttpStatus.NOT_MODIFIED.value(),"商品卖完了。");
        }

        return new ResponseEntity(returnOrder);
    }
}
